package org.example;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂并配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        //2.通过工厂创建连接，并获取channel
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        //3.创建队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //4.发送消息给队列
        System.out.println("===生产者开始生产消息===");
        long startTime = System.currentTimeMillis();

        channel.basicPublish("", QUEUE_NAME, null, "hello world".getBytes());

        long endTime = System.currentTimeMillis();
        System.out.println("===生产者完成生产消息===");
        System.out.println("生产时间：" + (endTime - startTime) + "ms");
    }
}

public class Consumer01 {
    private static final String CONSUMER_TAG = "Consumer01";

    public static void main(String[] args) throws IOException, TimeoutException {
        //建立连接
        Channel channel = ConnectionUtils.getChannel();
        //声明队列
        channel.queueDeclare(Constant.QUEUE_NAME_1, false, false, false, null);
        //消费消息
        channel.basicConsume(Constant.QUEUE_NAME_1, true, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(CONSUMER_TAG + "的消息：" + new String(body));
            }
        });
    }
}




public class Consumer02 {
    private static final String CONSUMER_TAG = "Consumer02";

    public static void main(String[] args) throws IOException, TimeoutException {
        //建立连接
        Channel channel = ConnectionUtils.getChannel();
        //声明队列
        channel.queueDeclare(Constant.QUEUE_NAME_1, false, false, false, null);
        //消费消息
        channel.basicConsume(Constant.QUEUE_NAME_1, true, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(CONSUMER_TAG + "的消息：" + new String(body));
            }
        });
    }
}